<?php


namespace app\api\controller;


use think\Db;

class Init
{
    /**
     * use   生成数据字典html代码
     * user  Hugh
     * date  2021/7/19 8:59
     */
    public function index()
    {
        $database = 'puqi'; // 库名
        $namesSql = 'select table_name,table_comment from information_schema.tables where table_schema="'.$database.'"';
        $names = DB::query($namesSql); // 所有的表名

        //获取每张表下面的字段名,数据类型,大小,备注
        $tableInfo = [];
        $wordHtml = '<a href="#top" style="position:fixed;top:50px;right:50px;">回到顶部</a><div style="height:10px;width:10px;" id="top"></div><ul>';
        foreach($names as $k =>$v)
        {
            $comment = empty($v['table_comment']) ? $v['table_name'] : $v['table_comment'];
            $wordHtml .= '<li><a href="#'.$v['table_name'].' '.$v['table_comment'].'"> '.$comment.'</a>
            </li>';
            $sql = "select COLUMN_NAME as 'field',
                IS_NULLABLE as 'isNull',
                COLUMN_TYPE as 'length',COLUMN_COMMENT as 'remark'
                from information_schema.columns where table_schema = '".$database."' and table_name = '".$v['table_name']."' ; ";
            $info = DB::query($sql);
            $tableInfo[$v['table_name'].' '.$v['table_comment']] = $info;
        }
        $wordHtml .= '</ul>';
        $table = '<style>
                    table, th, td {
                        border: 1px solid black;
                    }
                    table {
                      border-collapse: collapse;
                    }
                    th{
                        background:#F1E1FF;
                        font-size:18px;
                        font-weight: bold;
                        padding:5px;
                    }
                    td{
                        font-size:14px;
                        padding:5px;
                    }
                 </style>';
        $i = 1;
        foreach($tableInfo as $k =>$v)
        {
            $table .= '
            <h3>'.$i.'.'.$k.'</h3>
                <table id="'.$k.'">
                    <tr>
                        <th>字段名</th>
                        <th>可为空</th>
                        <th>字段类型</th>
                        <th>描述</th>
                    </tr>';
            foreach($v as $k1 =>$v1)
            {
                $td = '
                    <tr>';
                foreach($v1 as $k2 =>$v2)
                {
                    $td .= '<td>'.$v2.'</td>
                           ';
                }
                $td .= '
                    </tr>';
                $table .= $td;
            }
            $table .= '
               </table>';
            $i++;
        }
        $wordHtml .= $table;
        echo $wordHtml; die;

    }
}